package server

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"smart-weekly-report/models"
	"strings"
)

// Genkit服务结构
type GenkitService struct {
	APIKey string
}

func NewGenkitService(apiKey string) *GenkitService {
	return &GenkitService{APIKey: apiKey}
}

// AI生成周报内容
func (gs *GenkitService) GenerateReportContent(commits []models.GitCommit) (string, error) {
	// 构建提示词
	prompt := gs.buildPrompt(commits)

	// 调用Genkit API
	response, err := gs.callGenkitAPI(prompt)
	if err != nil {
		return "", err
	}

	return response, nil
}

// 构建AI提示词
func (gs *GenkitService) buildPrompt(commits []models.GitCommit) string {
	var commitMessages []string
	for _, commit := range commits {
		commitMessages = append(commitMessages, fmt.Sprintf("- %s: %s", commit.Author, commit.Message))
	}

	commitSummary := strings.Join(commitMessages, "\n")

	prompt := fmt.Sprintf(`请根据以下Git提交记录生成一份专业的工作周报：

本周工作内容：
%s

要求：
1. 按照STAR法则（情境、任务、行动、结果）组织内容
2. 使用专业的职场语言，包含"闭环思维"、"赋能业务"、"颗粒度细化"等术语
3. 突出技术难点和解决方案
4. 包含量化成果和数据分析
5. 总结本周收获和下周计划

请生成结构清晰、专业规范的周报：`, commitSummary)

	return prompt
}

// 调用Genkit API
func (gs *GenkitService) callGenkitAPI(prompt string) (string, error) {
	requestBody := map[string]interface{}{
		"model": "gemma",
		"messages": []map[string]string{
			{"role": "user", "content": prompt},
		},
		"max_tokens": 2000,
	}

	jsonData, _ := json.Marshal(requestBody)

	req, err := http.NewRequest("POST", "https://api.genkit.dev/v1/chat/completions", bytes.NewBuffer(jsonData))
	if err != nil {
		return "", err
	}

	req.Header.Set("Authorization", "Bearer "+gs.APIKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)

	var result map[string]interface{}
	json.Unmarshal(body, &result)

	if choices, ok := result["choices"].([]interface{}); ok && len(choices) > 0 {
		if choice, ok := choices[0].(map[string]interface{}); ok {
			if message, ok := choice["message"].(map[string]interface{}); ok {
				if content, ok := message["content"].(string); ok {
					return content, nil
				}
			}
		}

		return "", fmt.Errorf("API调用失败")
	}
	return "", fmt.Errorf("API调用失败: 无法从响应中提取内容")
}
